import {
  ajaxFun
} from "../../../../utils/ajax";


Page({

  data: {
    page: 1, //页数
    limit: 5, //条数
    list: [],
    title:""
  },
  onLoad(options) {
    if (options.title) {//"购买页面"过来的
      this.setData({
        title:options.title
      })
    }
    this.getList()
  },
  goBack(e){//返回上一个页面 修改上一个页面数据
     if(this.data.title){
         let i=e.currentTarget.dataset.index;
            let pageArry=getCurrentPages();//获取页面实例数组
          let prePage=pageArry[pageArry.length-2];//找到上一个页面
          prePage.setData({
            address:this.data.list[i]
          },()=>{
            wx.navigateBack({
              delta:1
            })
          })
     }
  },


  async getList() { //地址列表
    console.log("获取地址列表");
    let {
      list
    } = await ajaxFun("/address/list", "get", {
      page: this.data.page,
      limit: this.data.limit
    })
    if (list.length == 0) {
      wx.showToast({
        title: '暂无数据',
        icon: "none"
      })
    }
    this.setData({
      list: [...this.data.list, ...list] //扩展运算
    })
  },
  onReachBottom() { //分页加载
    console.log("到底部了改请求第二页");
    this.setData({
      page: ++this.data.page
    }, () => {
      this.getList()
    })
  },
  async chooseDefault(e) { //默认地址

    let i = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;

    let res = await ajaxFun("/address/default/set", "post", {
      id
    })
    this.setData({
      page: 1,
      list: []
    }, () => {
      this.getList()
    })
    // 前端效果
    // let list=this.data.list;
    // list.map((item,index)=>{
    //       i==index?item.isDefault=true:item.isDefault=false
    // })

    // this.setData({list})
  },
  del(e) {
    let id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '',
      content: '是否删除该地址',
      complete: (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          this.delFun(id)
        }
      }
    })



  },
  async delFun(id) {
    let res = await ajaxFun("/address/del", "post", {
      id
    })
    this.setData({
      page:1,
      list:[]
    },()=>{
      this. getList()
    })
  },
  goAddress(){//添加
    wx.navigateTo({
      url: '/myPackage/pages/users/user_address_add/index',
    })
  },
  editorAddress(e){
     let i=e.currentTarget.dataset.index;//拿到当前的索引
    let {id,isDefault,realName,phone,province,city,district,detail}=this.data.list[i]
     let obj={id,isDefault,realName,phone,province,city,district,detail};
     let str=JSON.stringify(obj)
     wx.navigateTo({
      url: `/myPackage/pages/users/user_address_add/index?address=${str}`,
    }) 
  }


})